package cn.huyanbing.middleware.thread.research;

import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

/**
 * @BelongProject middleware
 * @BelongPackage cn.huyanbing.middleware.thread.research
 * @Description 参考：https://www.cnblogs.com/suger43894/p/12738059.html
 * @ClassName ThreadAndWaitCompare
 * @Author huyangbing
 * @Date 2024/11/19 19:51
 * @Version 1.0.0
 */
public class ThreadAndWaitCompare {


    static  Object lock=new Object();

    public static void main(String[] args) {


        testSyncWait();


    }

    private  static void testSleep(){
        //sleep  无法唤醒 只能等待超时
        Stream.of("线程1", "线程2").forEach(s -> {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println(String.format("Thread %s  -- begin",s ));
                        TimeUnit.SECONDS.sleep(1);

                        System.out.println(String.format("Thread %s  -- end",s ));
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            },s).start();


        });
    }


    private  static void testWait(){
        //sleep  无法唤醒 只能等待超时
        Stream.of("线程1", "线程2").forEach(s -> {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println(String.format("Thread %s  -- begin",s ));

                        lock.wait(1000);

                        System.out.println(String.format("Thread %s  -- end",s ));
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            },s).start();


        });
    }


    private  static void testSyncWait(){
        //sleep  无法唤醒 只能等待超时
        Stream.of("线程1", "线程2").forEach(s -> {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    synchronized (lock){

                        try {
                            System.out.println(String.format("Thread %s  -- begin",s ));

                            lock.wait(1000);

                            System.out.println(String.format("Thread %s  -- end",s ));
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }

                    }

                }
            },s).start();


        });
    }
}
